package org.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@Service
public class OrderService {
    @Autowired
    PlatformTransactionManager transactionManager;

    @Autowired
    JdbcTemplate jdbcTemplate;

    public void usejdbc() {
        try {
            // 加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_demo?serverTimezone=Asia/Shanghai", "root", "root");
            PreparedStatement preparedStatement = connection.prepareStatement("update user_order set sale = ? where user = ?");
            preparedStatement.setString(1, "88");
            preparedStatement.setString(2, "zhangsan");
            preparedStatement.execute();
            preparedStatement.close();
            connection.close();
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void change() {
        jdbcTemplate.update("update user_order set sale = ? where user = ?", 9, "zhangsan");
    }

    public void change2() {
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        TransactionStatus transaction = transactionManager.getTransaction(defaultTransactionDefinition);
        jdbcTemplate.update("update user_order set sale = ? where user = ?", 99, "zhangsan");
//        try {
//            int i = 1 / 0;
//        } catch (Exception e) {
//
//        }

        int i = 1 / 0;
        transactionManager.commit(transaction);
    }


    @Transactional
    public void saleOrder() {
        jdbcTemplate.update("update user_order set sale = ? where user = ?", 99, "zhangsan");
        int i = 1 / 0;
    }
}
